package com.ball.dev.service.impl;

import cn.hutool.core.lang.UUID;

import com.ball.common.dtos.ResponseResult;
import com.ball.common.utils.IFileStorage;
import com.ball.dev.service.IFileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * <p>
 * 文件表，可以是普通文件、图片等 服务实现类
 * </p>
 *
 *  @author lou
 *  * @since 2023-12-07
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FileServiceImpl implements IFileService {

    private final IFileStorage fileStorage;

    @Override
    public ResponseResult uploadFile(MultipartFile file) {
        // 1.获取文件名称
        String originalFilename = file.getOriginalFilename();
        // 2.生成新文件名
        String filename = generateNewFileName(originalFilename);
        // 3.获取文件流
        InputStream inputStream;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException("文件读取异常", e);
        }
        // 4.上传文件
        String requestId = fileStorage.uploadFile(filename, inputStream);
        // 5.返回
        return ResponseResult.okResult(requestId);
    }

    @Override
    public void removeById(String id) {
        fileStorage.deleteFile(id);
    }


    private String generateNewFileName(String originalFilename) {

        // 1.获取后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        // 2.生成新文件名
        return UUID.randomUUID().toString(true) + "." + suffix;
    }
}
